package com.chookss.home.audit.project;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.audit.clockIn.ClockInRecordActivity;
import com.chookss.home.entity.ContactEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.ClearMoreZeroUtil;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.CircleImageView;
import com.chookss.view.DrawableTextView;
import com.chookss.view.consecutivescroller.ConsecutiveScrollerLayout;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.base.LoadingFragment;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

@SuppressLint("ValidFragment")
public class GroupCostFragment extends LoadingFragment implements OnRefreshListener, OnLoadMoreListener {

    public Context mContext;
    Unbinder unbinder;
    @BindView(R.id.rvView)
    RecyclerView rv;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.logscl)
    ConsecutiveScrollerLayout logscl;
    @BindView(R.id.logNoneTv)
    TextView logNoneTv;
    private CostAdapter adapter;
    private List<ContactEntity> list = new ArrayList<>();
    private int currentPage = 1;
    private String pageSize = "20";
    private boolean isEnd = false;//是否到底
    private String groupCode="",groupName="";
    public GroupCostFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cost, container, false);
        unbinder = ButterKnife.bind(this, view);
        return view;
    }



    @Override
    public void initData() {
        logNoneTv.setText("暂无数据");
        rv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        adapter = new CostAdapter(R.layout.item_group_role, getActivity(), list);
        ((SimpleItemAnimator) rv.getItemAnimator()).setSupportsChangeAnimations(false);
        rv.setAdapter(adapter);
        getData();
    }

    private RefreshLayout refreshLayout;
    public void setGroupCode(String code,String name) {
        groupCode=code;
        groupName=name;
    }
    @Override
    public void onRefresh(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        isEnd = false;
        currentPage = 1;
        getData();
    }

    @Override
    public void onLoadMore(@androidx.annotation.NonNull final RefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        if (isEnd) {//has next page
            MyToast.show("没有更多数据了");
            loadEnd();
        } else {
            currentPage++;
            getData();
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("groupCode", groupCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<ContactEntity>>>() {
        }.getType(), null, Urls.selectItemDakaEmpByItemCode, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<ContactEntity>>() {
            @Override
            public void onSuccess(List<ContactEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (rv == null || llNone == null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex, data.size());
                    rv.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        rv.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();

            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }


    private void loadEnd() {
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Refreshing)
            refreshLayout.finishRefresh(true);
        if (null != refreshLayout && refreshLayout.getState() == RefreshState.Loading)
            refreshLayout.finishLoadMore(true);
    }


    class CostAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Activity context;

        public CostAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity entity) {
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvPost = helper.getView(R.id.tvPost);
            LinearLayout llNum = helper.getView(R.id.llNum);
            DrawableTextView tvNum = helper.getView(R.id.tvNum);
            CircleImageView ivImg = helper.getView(R.id.ivImg);
            View line = helper.getView(R.id.line);
            llNum.setVisibility(View.VISIBLE);
            GlideUtils.loadAvatar(mContext,entity.getHeadPhotoThumbUrl(),ivImg);
            tvName.setText(entity.getEmployeeName());
            tvPost.setText(entity.getPostName());
            float shangBanNum=Utils.changeFloat(entity.getShangBanNum());
            float xiaBanNum=Utils.changeFloat(entity.getXiaBanNum());
            tvNum.setText(ClearMoreZeroUtil.subZeroAndDot((shangBanNum+xiaBanNum)+""));
            if(helper.getItemPosition()==0){
                line.setVisibility(View.GONE);
            }else{
                line.setVisibility(View.VISIBLE);
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    Intent intent=new Intent(mContext, ClockInRecordActivity.class);
                    intent.putExtra("employeeCode",entity.getEmployeeCode());
                    intent.putExtra("groupCode",groupCode);
                    mContext.startActivity(intent);
                }
            });
            ivImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent=new Intent(mContext, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode",entity.getEmployeeCode());
                    mContext.startActivity(intent);
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();

    }

}
